let imageLoading = false //判断数据是否在加载
let imageList = []  // 存放所有的图片
let zoomNum = 1 // 全屏图片缩放比例
let nextContinuationToken = "";
let finished = false;
$(".hint").hide()

var fileNodeMap = new Map();

function addFileNode(fileNodeList) {
    if(fileNodeList.length == 0) {
        finished = true;
        return;
    }
    for(var i = 0; i <　fileNodeList.length; i++) {
        var node = fileNodeList[i];
        var fileNode = new Object();
        fileNode.fileName = node.fileName;
        fileNode.path = node.path;
        fileNode.size = node.size;
        fileNode.lastModified = node.lastModified;
        fileNode.type = node.type;
        fileNode.imgUrl = node.imgUrl;
        fileNodeMap.set(node.fileName, fileNode);
    }
}

// 获取图片 并 渲染
function getImageList() {
    if(finished) {
        return;
    }
    imageLoading = true
    $(".hint").show()
    let pageSize = 15;
    let path = $("#path").html();
    $.ajax({
        type: "get",
        dataType: 'json',
        url: "/admin/nas/listByPath?path=" + path + "&pageSize=" + pageSize + "&nextContinuationToken=" + nextContinuationToken,
        success(data) {
            addFileNode(data.list.list);
            nextContinuationToken = data.list.nextContinuationToken;
            imageLoading = false;
            $(".hint").hide();
            fallsRendering(data.list.list);
        }
    })
}

getImageList();

// 1. 渲染图片
function fallsRendering(fileNodeList) {
    let html = ""
    for(var i = 0; i <　fileNodeList.length; i++) {
        if (fileNodeList[i].type == "image") {
        html += `
            <div class="item">
                <div class="item-img">
                    <img data-src="${fileNodeList[i].imgUrl}" alt="" file-name="${fileNodeList[i].path}" file-type="${fileNodeList[i].type}">
                </div>
                <div class="file-name">${fileNodeList[i].fileName}</div>
            </div>
              `
        } else {
             html += `
             <div class="item">
                 <div class="item-img">
                     <img data-src="/static/nas/img/${fileNodeList[i].type}.png" alt="" file-name="${fileNodeList[i].path}" file-type="${fileNodeList[i].type}">
                 </div>
                 <div class="file-name">${fileNodeList[i].fileName}</div>
             </div>
               `
         }
    }
    $(".box").append(html)
    lazyLoadingImage()
}



// 2. 滚到到底部加载更多
$(window).scroll(function () {
    lazyLoadingImage()
    const pageHeight = $(document).height();//页面的总高度
    const windowHeight = $(window).height();//可视区高度
    const scrollTop = $(window).scrollTop();//滚动条距离顶部的高度
    const totalHeight = pageHeight - windowHeight - scrollTop  // 计算的高度
    if (Math.floor(totalHeight) <= 500 && !imageLoading) {
        getImageList();
    }
});


// 3. 图片懒加载
function lazyLoadingImage() {
    const boxHeight = $(".box").height()
    const windowHeight = $(window).height(); //可视区高度
    const scrollTop = $(window).scrollTop();//滚动条距离顶部的高度
    $(".box .item img").each(function () {
        let imageTop = $(this).offset().top
        if (imageTop - scrollTop <= windowHeight) {
            $(this).attr("src", $(this).data("src"))
        }
    })
    //当加载的图片高度没有页面高度时 再次加载
    if (boxHeight < windowHeight) {
        getImageList()
    }
}

function showBigImage(fileName) {
    $.ajax({
        type: "get",
        dataType: 'json',
        url: "/admin/nas/showImgFile?path=" + fileName,
        success(data) {
            let imgSrc = data.url;
            attrImage(imgSrc)
            fullScreen();
            recoverScale();
        }
    })
}

function showDocFile(fileName) {
    $.ajax({
        type: "get",
        dataType: 'json',
        url: "/admin/nas/showDocFile?path=" + fileName,
        success(data) {
            let previewUrl = data.url;
            window.open(previewUrl, "_blank");
        }
    });
}

function showFolder(fileName) {
    var url = "/admin/nas/indexNew?path=" + fileName;
    window.open(url, "_self");
}

function showMediaFile(fileName) {
    $.ajax({
        type: "get",
        dataType: 'json',
        url: "/admin/nas/showMediaFile?path=" + fileName,
        success(data) {
            let mediaUrl = data.url;
            window.open(mediaUrl, "_blank");
        }
    });
}

function showFileUrl(fileName) {
    $.ajax({
        type: "get",
        dataType: 'json',
        url: "/admin/nas/showFileUrl?path=" + fileName,
        success(data) {
            let fileUrl = data.url;
            window.open(fileUrl, "_blank");
        }
    });
}


// 4. 点击图片放大全屏
let imgIndex = null; // 图片的索引
$(".box").on("click", "div", function () {
    var fileName = $(this).find("img").attr("file-name");
    var fileType = $(this).find("img").attr("file-type");
    if(fileType == "image") {
        showBigImage(fileName);
    } else if(fileType == "folder"){
        showFolder(fileName);
    } else if(fileType == "pdf" || fileType == "doc" || fileType == "excel" || fileType == "ppt") {
        showDocFile(fileName);
    } else if(fileType == "audio" || fileType == "video") {
        showMediaFile(fileName);
    } else {
        showFileUrl(fileName);
    }
})

$("#fullScreen .close").click(() => {
    exitFullscreen();
})
$("#fullScreen .upward").click(() => {
    imgIndex = (imgIndex == 0) ? 0 : --imgIndex
    attrImage(imgIndex)
    recoverScale()  // 图片恢复大小
})
$("#fullScreen .down").click(() => {
    let imageAll = $(".box .item").length
    imgIndex = (imgIndex == imageAll) ? imageAll : ++imgIndex
    attrImage(imgIndex)
    recoverScale()  // 图片恢复大小
})


// 根据索引获取图片路径
function attrImage(imgSrc) {
    $("#fullScreen .content img").attr("src", imgSrc)
}

//退出全屏
$("#exitFullScreen").on("click", function () {
    exitFullscreen();
})




//fullScreen()和exitScreen()全屏化 有多种实现方式，此处只使用了其中一种
//全屏
function fullScreen() {
    var element = document.documentElement;
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    }
}

//退出全屏
function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    }
}
//监听window是否全屏，并进行相应的操作,支持esc键退出
window.onresize = function () {
    var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen ||
        document.msFullscreenElement || document.fullscreenElement
    );
    if (isFull) {  // true 全屏
        $("#fullScreen").css("display", "block");
        $("html").css("overflow", "hidden");
        // console.log("全屏");
    } else {
        $("#fullScreen").css("display", "none");
        $("html").css("overflow", "auto");

        // console.log("退出全屏");
    }
}


// 5. 鼠标齿轮放大缩小 图片
let box = document.getElementById('fullScreen');
addEvent(box, 'mousewheel', onMouseWheel);
addEvent(box, 'DOMMouseScroll', onMouseWheel);
function onMouseWheel(ev) {/*当鼠标滚轮事件发生时，执行一些操作*/
    var ev = ev || window.event;
    var down = true; // 定义一个标志，当滚轮向下滚时，执行一些操作
    down = ev.wheelDelta ? ev.wheelDelta < 0 : ev.detail > 0;
    if (down) { // true 鼠标滚轮向下  +++++++++ false 鼠标滚轮向上
        if (zoomNum <= 0.5) { return }
        $("#fullScreen .content img").css({
            transform: `scale(${zoomNum -= 0.1})`
        })


    } else {
        $("#fullScreen .content img").css({
            transform: `scale(${zoomNum += 0.1})`
        })


    }
    if (ev.preventDefault) {/*FF 和 Chrome*/
        ev.preventDefault();// 阻止默认事件
    }
    return false;
}

function addEvent(obj, xEvent, fn) {
    if (obj.attachEvent) {
        obj.attachEvent('on' + xEvent, fn);
    } else {
        obj.addEventListener(xEvent, fn, false);
    }
}

function recoverScale() {
    zoomNum = 1
    $("#fullScreen .content img").css({ transform: `scale(${zoomNum})` })
}